<?php

namespace common\rest\traits;

use Yii;
use yii\web\Link; // represents a link object as defined in JSON Hypermedia API Language.
use common\models\c2\entity\EntityAttachmentImage;
use common\models\c2\entity\EntityAttachmentFile;
use cza\base\models\statics\EntityModelStatus;
use yii\helpers\Url;

trait EntityModelTrait {

    public function getPageParamName($splitor = '-') {
        return "page";
    }

    public function getSortParamName($splitor = '-') {
        return "sort";
    }

    public function getPageSizeParam($splitor = '-') {
        return "page_size";
    }

    public function getLinks() {
        return [
            Link::REL_SELF => ['href' => Url::to(['view', 'id' => $this->id], true)],
            'index' => ['href' => Url::to(['index'], true)],
        ];
    }

    public function getAttachmentImage($attribute) {
        return $this->getAttachmentImages($attribute)->one();
    }

    public function getAllAttachments() {
        $condition = ['entity_class' => $this->getEntityClassName()];
        return $this->hasMany(EntityAttachmentImage::className(), ['entity_id' => 'id'])
                        ->andOnCondition($condition)
                        ->orderBy(['position' => SORT_DESC, 'id' => SORT_ASC]);
    }

    public function getAttachmentImages($attribute = 'album') {
        $condition = !empty($attribute) ? ['entity_class' => $this->getEntityClassName(), 'entity_attribute' => $attribute, 'status' => EntityModelStatus::STATUS_ACTIVE] : ['entity_class' => $this->getEntityClassName(), 'status' => EntityModelStatus::STATUS_ACTIVE];
        return $this->hasMany(EntityAttachmentImage::className(), ['entity_id' => 'id'])
                        ->andOnCondition($condition)
                        ->orderBy(['position' => SORT_DESC, 'id' => SORT_ASC]);
    }

    public function getAttachmentFiles($attribute = 'files') {
        return $this->hasMany(EntityAttachmentFile::className(), ['entity_id' => 'id'])
                        ->andOnCondition(['entity_class' => $this->getEntityClassName(), 'entity_attribute' => $attribute, 'status' => EntityModelStatus::STATUS_ACTIVE])
                        ->orderBy(['position' => SORT_DESC, 'id' => SORT_ASC]);
    }

}
